<template>
  <page-layout title="设备号：000001" logo="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png">
    <div class="warring-card">
      <a-button type="primary" @click="showModal" v-show="false">
        Modal
      </a-button>
      <a-modal v-model="visible" title="警告！" style="color: #cb7070" ok-text="确认" cancel-text="取消" @ok="hideModal"
               v-show="acknowledge">
        <p v-show="visibleCH4">甲烷浓度超标！！请及时检修</p>
        <p v-show="visibleCH4">当前CH4浓度：{{ cover.ch4 }}mg/m³</p>


        <p v-show="visibleCO">CO浓度超标！！请及时检修</p>
        <p v-show="visibleCO">当前CO浓度：{{ cover.co }}mg/m³</p>


      </a-modal>
      <!--      <br/>-->
      <!--      <br/>-->
      <!--      <a-button @click="confirm">-->
      <!--        Confirm-->
      <!--      </a-button>-->
    </div>
    <detail-list size="small" :col="2" slot="headerContent">
      <detail-list-item term="设备名称">测试设备一号</detail-list-item>
      <detail-list-item term="设备分类">雨水井盖</detail-list-item>
      <detail-list-item term="安装时间">2021-03-27</detail-list-item>
      <detail-list-item term="工作日期">2021-03-27 ~ {{ today }}</detail-list-item>
      <detail-list-item term="备注">测试用原型一号机</detail-list-item>
    </detail-list>
    <template class="transparent-card" slot="extra">
      <head-info title="状态" content="浓度超标！" v-if="buttontype"/>
      <head-info title="状态" content="正常运行" v-else/>
      <head-info title="累计运行时间" content="145 h"/>
    </template>
    <template slot="action">
      <!--      <a-button-group style="margin-right: 8px;">-->
      <!--        <a-button>操作</a-button>-->
      <!--        <a-button>操作</a-button>-->
      <!--        <a-button><a-icon type="ellipsis"/></a-button>-->
      <!--      </a-button-group>-->
      <a-button type="danger" style="margin-right: 30px;" @click="checkShow" v-if="buttontype">警告</a-button>
      <a-button type="primary" style="margin-right: 30px;" v-else>正常</a-button>


    </template>
    <!--    <a-card :bordered="false" title="流程进度">-->
    <!--      <a-steps :current="1" progress-dot :direction="isMobile ? 'vertical' : 'horizontal'">-->
    <!--        <a-step title="创建项目">-->
    <!--          <a-step-item-group :align="isMobile ? 'left' : 'center'" slot="description">-->
    <!--            <a-step-item link="/dashboard/workplace" title="曲丽丽" icon="dingding-o"/>-->
    <!--            <a-step-item title="2016-12-12 12:32"/>-->
    <!--          </a-step-item-group>-->
    <!--        </a-step>-->
    <!--        <a-step title="部门初审">-->
    <!--          <a-step-item-group :align="isMobile ? 'left' : 'center'" slot="description">-->
    <!--            <a-step-item link="/form/step" title="周毛毛" icon="dingding-o" />-->
    <!--            <a-step-item link="/result/success" title="催一下" icon="bell"/>-->
    <!--          </a-step-item-group>-->
    <!--        </a-step>-->
    <!--        <a-step title="财务复核">-->
    <!--        </a-step>-->
    <!--        <a-step title="完成">-->
    <!--        </a-step>-->
    <!--      </a-steps>-->
    <!--    </a-card>-->
    <a-row style="margin: 0 -12px">
      <a-col style="padding: 0 4px; margin: 8px 0" :xxl="18" :xl="18" :lg="24" :md="24" :sm="24" :xs="24">
        <a-card class="transparent-card" :bordered="false" title="设备信息">
          <detail-list>
            <detail-list-item term="设备名称">测试设备一号</detail-list-item>
            <detail-list-item term="设备ID">000001</detail-list-item>
            <detail-list-item term="当前状态">正常</detail-list-item>
            <detail-list-item term="充能方式">太阳能供电</detail-list-item>
            <detail-list-item term="设备安装地址">滨湖道</detail-list-item>
          </detail-list>
          <detail-list title="详细信息：">
            <detail-list-item term="数据ID">725</detail-list-item>
            <detail-list-item term="该数据更新时间">{{ today }}</detail-list-item>
          </detail-list>
<!--          实时信息，但表头是白色的，暂未解决，于是注释掉-->
<!--          <a-descriptions-->
<!--              class="a-description"-->
<!--              title="实时信息"-->
<!--              bordered-->
<!--              :column="{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }"-->
<!--          >-->
<!--            <a-descriptions-item label="当前温度">-->
<!--              {{ cover.temp }} ℃-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="湿度">-->
<!--              {{ cover.hum }} %rh-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="甲烷浓度">-->
<!--              {{ cover.ch4 }} mg/m³-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="一氧化碳浓度">-->
<!--              {{ cover.co }} mg/m³-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="俯仰角">-->
<!--              {{ cover.pitch }} °-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="电量">-->
<!--              {{ cover.roll }} %-->
<!--            </a-descriptions-item>-->
<!--            <a-descriptions-item label="时间戳">-->
<!--              {{ cover.time }}-->
<!--            </a-descriptions-item>-->
<!--          </a-descriptions>-->
          <br/>
<!--          bordered -> 带边框属性，加了会出现白色背景-->
          <a-descriptions
              title="硬件信息"
              :column="{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }"
          >
            <a-descriptions-item label="温湿度传感器">
              DHT11
            </a-descriptions-item>
            <a-descriptions-item label="气体传感器">
              MQ-4
            </a-descriptions-item>
            <a-descriptions-item label="无线传输模块">
              NB-IoT
            </a-descriptions-item>
            <a-descriptions-item label="一氧化碳传感器">
              MQ-7
            </a-descriptions-item>
            <a-descriptions-item label="电池型号">
              3.7V锂电池
            </a-descriptions-item>
            <a-descriptions-item label="供能板块">
              太阳能板-APM18M5W27x27
            </a-descriptions-item>
            <a-descriptions-item label="备注">
              测试用设备一号机
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
        <a-card id="list-card" class="project-list" style="margin-bottom: 15px;" :bordered="false" :title="'实时监控信息'" :body-style="{padding: 0}">
          <div>
            <!--              item虽然没用但是不要删除-->
            <a-card-grid :key="i" v-for="(item, i) in 6">
              <a-card class="card" :bordered="false" :body-style="{padding: 0}">
                <a-card-meta class="card-meta" style="font-size: 30px;font-weight: bolder" :description="coverMsg[i]">
                  <div slot="title" class="card-title">
                    <a-avatar size="small" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
                    <span>{{columns[i].title}}</span> <!--监控信息卡片标题-->
                  </div>
                </a-card-meta>
                <div class="project-item">
                  <a class="group" href="/#/">{{ cover.deviceName }}</a>
                  <span class="datetime">{{cover.time}}</span>
                </div>
              </a-card>
            </a-card-grid>
          </div>
        </a-card>
      </a-col>
      <a-col style="padding: 0 4px; margin: 8px 0" :xxl="6" :xl="6" :lg="24" :md="24" :sm="24" :xs="24">
        <!--          雷达图-->
        <a-card class="transparent-card" :title="`雷达图监控`" style="margin-bottom: 4px; padding: 8px 0" :bordered="false"
                :body-style="{padding: 0}">
          <div style="min-height: 320px;">
<!--            <radar :my-cover="cover"/>-->
            <new-rander id="1" />
          </div>
        </a-card>
        <a-card class="transparent-card" :title="'设备电量'" :bordered="false" style="margin: 16px 0">
          <battery v-if="dataComplete"></battery>
        </a-card>
      </a-col>
    </a-row>
    <br/>

    <a-row style="margin: 0 -12px">
      <a-col style="padding: 0 4px; margin: 8px 0" :xxl="8" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
        <!--          雷达图-->
        <a-card class="transparent-card" :title="`雷达图监控`" style="margin-bottom: 4px" :bordered="false"
                :body-style="{padding: 0}">
          <div style="min-height: 320px;">
<!--            <radar :my-cover="cover"/>-->
            <new-rander id="2" />
          </div>
        </a-card>
      </a-col>
      <a-col style="padding: 0 4px; margin: 8px 0" :xxl="8" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
        <!--          温度计-->
        <a-card class="transparent-card" :title="'温湿度监控'" style="margin-bottom: 4px" :bordered="false" :body-style="{padding: 0}">
          <liquidity v-if="dataComplete" :temp="cover.temp" :hum="cover.hum"></liquidity>
        </a-card>
        <!--          仪表盘-->
        <a-card class="transparent-card" :title="'有害气体监控'" :bordered="false">
          <gauge-for-two v-if="dataComplete" :co="cover.co" :ch4="cover.ch4"></gauge-for-two>
        </a-card>
      </a-col>
      <a-col style="padding: 0 4px; margin: 8px 0" :xxl="8" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
        <!--          电量显示-->
        <a-card class="transparent-card" :title="'设备电量'" :bordered="false" style="margin-bottom: 4px; height: 200px">
          <battery></battery>
        </a-card>
        <a-card class="transparent-card" :title="'设备情况'" style="margin-bottom: 4px" :bordered="false"
                :body-style="{padding: 0}">
          <area-line/>
        </a-card>
      </a-col>
    </a-row>
    <!--    中间的两个表-->
    <a-row style="margin: 0 -12px">
      <a-col style="padding: 0 12px" :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
        <a-card class="transparent-card" title="一氧化碳浓度">
          <div>
            <br><br><br><br>
            <mini-area :mylist="coList"></mini-area>
          </div>
        </a-card>
      </a-col>
      <a-col style="padding: 0 12px" :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
        <a-card class="transparent-card" title="甲烷浓度">
          <br><br><br><br>
          <mini-area :mylist="ch4List"></mini-area>
        </a-card>
      </a-col>
    </a-row>

    <a-card class="transparent-card" style="margin-top: 24px;" :bordered="false" title="设备历史记录">
      <a-table :columns="columns" :data-source="historyList" :style="{fontSize: '30px'}">
        <span slot="temp" slot-scope="text">{{ text }}℃</span>
        <span slot="hum" slot-scope="text">{{ text }}%rh</span>
        <span slot="ch4" slot-scope="text">{{ text }}mg/m³</span>
        <span slot="co" slot-scope="text">{{ text }}mg/m³</span>
        <span slot="pitch" slot-scope="text">{{ text }}°</span>
        <span slot="battery" slot-scope="text">{{ text }}96%</span>
        <span slot="time" slot-scope="text">{{ text }}</span>
      </a-table>
    </a-card>
    <a-card
        class="transparent-card"
        style="margin-top: 24px"
        :bordered="false"
        :tabList="tabList"
        :activeTabKey="activeTabKey"
        @tabChange="(key) => {this.activeTabKey = key}"
    >
      <a-table
          class="transparent-card"
          v-if="activeTabKey === '1'"
          :columns="operationColumns"
          :dataSource="operation1"
          :pagination="false"
      />
      <a-list></a-list>
      <!--      <a-table-->
      <!--        v-if="activeTabKey === '2'"-->
      <!--        :columns="operationColumns"-->
      <!--        :dataSource="operation2"-->
      <!--        :pagination="false"-->
      <!--      />-->
      <!--      <a-table-->
      <!--        v-if="activeTabKey === '3'"-->
      <!--        :columns="operationColumns"-->
      <!--        :dataSource="operation3"-->
      <!--        :pagination="false"-->
      <!--      />-->
    </a-card>
  </page-layout>
</template>

<script>
import PageLayout from '@/layouts/PageLayout'
import DetailList from '@/components/tool/DetailList'
import {operation1, operation2, operation3, operationColumns} from '@/mock/common/tableData'
import {mapState} from 'vuex'
import HeadInfo from '@/components/tool/HeadInfo';
import axios from "axios";
import {format} from 'date-fns'
import MiniArea from "@/components/chart/MiniArea";
import cover from '../../evntBus';
// import Radar from "@/components/chart/Radar";
import Liquidity from "@/pages/components/echarts/Liquidity";
import GaugeForTwo from "@/pages/components/echarts/GaugeForTwo";
import Battery from "@/pages/components/echarts/Battery";
import AreaLine from "@/pages/components/echarts/AreaLine";
import NewRander from "@/pages/components/echarts/NewRander";

const DetailListItem = DetailList.Item

//const AStepItemGroup = AStepItem.Group


// 设备历史记录的表头
const columns = [
  {
    title: '温度',
    key: 'temp',
    dataIndex: 'temp',
    scopedSlots: {customRender: 'temp'},
  },
  {
    title: '湿度',
    key: 'hum',
    dataIndex: 'hum',
    scopedSlots: {customRender: 'hum'},
  },
  {
    title: '甲烷浓度',
    dataIndex: 'ch4',
    key: 'ch4',
    scopedSlots: {customRender: 'ch4'},
  },
  {
    title: '一氧化碳浓度',
    key: 'co',
    dataIndex: 'co',
    scopedSlots: {customRender: 'co'},
  },
  {
    title: '俯仰角',
    key: 'pitch',
    dataIndex: 'pitch',
    scopedSlots: {customRender: 'pitch'},
  },
  {
    title: '电量',
    key: 'battery',
    dataIndex: 'battery',
    scopedSlots: {customRender: 'battery'},
  }
];

const tabList = [
  {
    key: '1',
    tab: '操作日志'
  },
  // {
  //   key: '2',
  //   tab: '操作日志二'
  // },
  // {
  //   key: '3',
  //   tab: '操作日志三'
  // }
]

export default {
  name: 'AdvancedDetail',//AStepItemGroup, AStepItem,
  components: {
    NewRander,
    AreaLine,
    Battery,
    GaugeForTwo, Liquidity, MiniArea, HeadInfo, DetailListItem, DetailList, PageLayout
  },
  data() {
    return {
      tablename: "datas",
      visibleCH4: false,
      visibleCO: false,
      visible: false,
      acknowledge: true,
      buttontype: false,
      dataComplete: false,
      timer: null,
      // 其实不需要写这么详细，只用cover:null即可，初始化是为了防止接口返回值出问题时页面空空的不好看
      cover: {
        deviceName: '测试设备一号',
        time: '2021/04-01/11:28:46',
        temp: '22',
        hum: "23",
        co: "2.6",
        ch4: "1.5",
        pitch: "0.25",
        roll: "1.0"
      },
      historyList: null,
      coList: [],
      ch4List: [],
      tabList,
      operationColumns,
      operation1,
      operation2,
      operation3,
      activeTabKey: '2',
      today: "",
      columns,
    }
  },
  computed: {
    ...mapState('setting', ['isMobile']),
    coverMsg: function () {
      // 因为数值为0时信息不显示，所以修改一下获取到零值时的显示方式
      let pitch, ch4, co
      this.cover.pitch === 0 ? pitch = "0.0" : pitch = this.cover.pitch
      this.cover.ch4 === 0 ? ch4 = "0.0" : ch4 = this.cover.ch4
      this.cover.co === 0 ? co = "0.0" : co = this.cover.co
      // this.cover.roll === 0 ? roll = "0.0" : roll = this.cover.roll
      console.log(this.cover)
      return [this.cover.temp, this.cover.hum, ch4, co, pitch, 96]
    }
  },
  mounted() {
    let self = this;
    cover.$on("sentCoverNameEventToAdvanceDetail", function (tablename) {
      self.tablename = tablename;
      console.log("AdvancedDetail:" + tablename)
    });
  },
  created() {
    // 每次进入界面时，先清除之前的所有定时器，然后启动新的定时器
    clearInterval(this.timer)
    this.timer = null
    this.setTimer()
    this.getToday()
    // 获取最新二十条设备信息作为历史记录
    this.getHistoryList()
    this.getNewMsg()
  },
  methods: {
    //获取当前年月日
    getToday() {
      const nowDate = new Date();
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      }
      const newMonth = date.month > 10 ? date.month : '0' + date.month
      const day = date.date > 10 ? date.date : '0' + date.date
      this.today = date.year + '-' + newMonth + '-' + day
    },
    // onTabChange (key) {
    //   console.log(key)
    // },
    // 定时器，定时5秒触发一次
    setTimer() {
      if (this.timer == null) {
        this.timer = setInterval(() => {
          // 定时触发的行为在这里
          this.getNewMsg()
          this.getHistoryList()
        }, 5000)
      }
    },
    getNewMsg() {
      axios.get("http://119.3.218.80:8080/getLatestOne" + "?tablename=" + this.tablename, {timeout: 2500})
          .then(res => {
            Object.assign(this.cover, res.data)
            if (res.data.co >= 40) {
              this.visible = true;
              this.visibleCO = true;
              this.buttontype = true;
            }
            if (res.data.ch4 >= 40) {
              this.visible = true;
              this.visibleCH4 = true;
              this.buttontype = true;
            }
            if (res.data.ch4 <= 40 && res.data.co <= 40) {
              this.visible = false;
              this.visibleCH4 = false;
              this.buttontype = false;
            }
            this.cover.time = res.data.time
            this.dataComplete = true
            this.cover = res.data
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
    },
    getHistoryList() {
      axios.get("http://119.3.218.80:8080/getLatestByNum/" + this.tablename + "/20")
          .then(response => {
            this.historyList = response.data
            let beginDay
            this.historyList.forEach(item => {
              beginDay = new Date(item.time).getTime();
              item.time = format(new Date(beginDay), "yyyy-MM-dd HH:mm:ss")
            })
            this.historyList.reverse()
          })
          .then(this.getNewMsgList())
          .catch(err => {
            console.log(err)
            this.$message.error('查询历史记录出错，请检查网络连接');
          })
    },
    getNewMsgList() {
      // 获取最新二十条一氧化碳和甲烷浓度作为波浪图表格记录
      axios.get("http://119.3.218.80:8080/getCOByNum?tablename=" + this.tablename + "&number=20")
          .then(response => {
            let beginDay
            response.data.reverse().forEach((item, index) => {
              beginDay = new Date(this.historyList[index].time).getTime();
              if (this.coList.length > 20) {
                for (let i = 0; i < 20; i++) {
                  this.coList.shift()
                }
              } else {
                this.coList.push({
                  x: format(new Date(beginDay), "HH:mm:ss"),
                  y: item
                })
              }
            })
          })
          .catch(err => {
            console.log(err)
            this.$message.error('查询一氧化碳信息出错，请检查网络连接');
          })
      axios.get("http://119.3.218.80:8080/getCH4ByNum?tablename=" + this.tablename + "&number=20")
          .then(response => {
            let beginDay
            response.data.reverse().forEach((item, index) => {
              beginDay = new Date(this.historyList[index].time).getTime();
              if (this.ch4List.length > 20) {
                for (let i = 0; i < 20; i++) {
                  this.ch4List.shift()
                }
              } else {
                this.ch4List.push({
                  x: format(new Date(beginDay), "HH:mm:ss"),
                  y: item
                })
              }
            })
          })
          .catch(err => {
            console.log(err)
            this.$message.error('查询甲烷浓度出错，请检查网络连接');
          })
    },
    showModal() {
      this.visible = true;
    },
    hideModal() {
      //this.visible = false;
      this.acknowledge = false;
      // this.visibleCO = false;
      // this.visibleCH4 = false;
    },
    checkShow() {
      this.acknowledge = true;
    },
  },
  // updated() {
  //   this.setTimer()
  // },
  beforeDestroy() {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer)
    this.timer = null
  }
}
</script>

<style lang="less" scoped>
@import "src/pages/dashboard/workplace/index";
.transparent-card {
  background-color: rgba(0,0,0,0.2) !important;
}
.a-description {
  background-color: rgba(0,0,0,0.1) !important;
}
.card {
  background-color: rgba(0, 0, 0, 0) !important;
}
.warring-card {
  color: #f0f0f0 !important;
}
::v-deep .ant-table-thead > tr > th {
  color: #f0f0f0;
  background: rgba(120, 120, 120, 0.2) !important; //如果不生效 记得加后面的这个important
}
</style>
